package org.example.springbook.Service;

import org.example.springbook.enums.BookStatusEnum;
import org.example.springbook.mapper.BookInfoMapper;
import org.example.springbook.model.BookInfo;
import org.example.springbook.model.PageRequest;
import org.example.springbook.model.PageResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 22652
 * Date: 2024-06-20
 * Time: 18:21
 */
@Service
public class BookService {

    private static final Logger log = LoggerFactory.getLogger(BookService.class);
    @Autowired
    private BookInfoMapper bookInfoMapper;


    public PageResult<BookInfo> selectBookInfoByPage(PageRequest pageRequest) {
        if (pageRequest == null) {
            return null;
        }
//获取总记录数
        Integer count = bookInfoMapper.count();

        List<BookInfo> infoList = bookInfoMapper.selectBookInfoByPage(pageRequest.getOffset(), pageRequest.getPageSize());
//获取当前记录
        if (infoList != null && !infoList.isEmpty()) {
            for (BookInfo bookInfo : infoList) {
                //根据status 获取状态的定义
                bookInfo.setStatusCN(BookStatusEnum.getNameByCode(bookInfo.getStatus()).getStatus());
            }
        }
        return new PageResult<>(infoList, count, pageRequest);
    }

    /*
     * 添加图书
     *
     * @param bookInfo
     * @return
     */

    public Integer addBook(BookInfo bookInfo) {
        Integer result = 0;
        try {
            result = bookInfoMapper.insertBook(bookInfo);
        } catch (Exception e) {
            log.error("添加图书出错, e:{}", e);
        }
        return result;
    }

    public BookInfo queryBookInfoById(Integer id) {
        return bookInfoMapper.queryBookInfoById(id);
    }

    /*
     * 更新图书
     * @param bookInfo
     * @return
     */
    public Integer updateBook(BookInfo bookInfo) {
        Integer result = 0;
        try {
            result = bookInfoMapper.updateBook(bookInfo);
        } catch (Exception e) {
            log.error("更新图书失败, e:{}", e);
        }
        return result;
    }

    public Integer batchDelete(List<Integer> ids) {
        Integer result = 0;
        try {
            result = bookInfoMapper.batchDelete(ids);
        } catch (Exception e) {
            log.error("批量删除图书失败, ids:{}", ids);
        }
        return result;
    }
}
